package com.wzb.mybatisplus.bitaction.formal;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BlockCypherBatchBalance {

    private static final String BLOCKCYPHER_URL = "https://api.blockcypher.com/v1/btc/main/addrs/";
    private final OkHttpClient client;
    private final ObjectMapper mapper;

    public BlockCypherBatchBalance() {
        this.client = new OkHttpClient();
        this.mapper = new ObjectMapper();
    }

    /**
     * 使用 BlockCypher API 批量查询
     */
    public Map<String, Object> getBatchBalance(List<String> addresses) throws IOException {
        // BlockCypher 支持批量查询，但有限制
        String addressList = String.join(";", addresses.subList(0, Math.min(addresses.size(), 10)));

        Request request = new Request.Builder()
                .url(BLOCKCYPHER_URL + addressList + "?limit=0")
                .get()
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("BlockCypher请求失败: " + response);
            }

            String responseBody = response.body().string();
            return parseBlockCypherResponse(responseBody);
        }
    }

    private Map<String, Object> parseBlockCypherResponse(String response) throws IOException {
        JsonNode root = mapper.readTree(response);
        Map<String, Object> result = new HashMap<>();

        if (root.isArray()) {
            // 批量响应
            for (JsonNode addrInfo : root) {
                String address = addrInfo.get("address").asText();
                long balance = addrInfo.get("final_balance").asLong();
                result.put(address, balance);
            }
        } else {
            // 单个地址响应
            String address = root.get("address").asText();
            long balance = root.get("final_balance").asLong();
            result.put(address, balance);
        }

        return result;
    }

    public static void main(String[] args) throws IOException {
        // 准备测试地址
        List<String> addresses = Arrays.asList(
                "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
                "1CounterpartyXXXXXXXXXXXXXXXUWLpVr",
                "1BitcoinEaterAddressDontSendf59kuE"
        );

        Map<String, Object> map = new BlockCypherBatchBalance().getBatchBalance(addresses);

        for(String s : addresses){
            System.out.println(map.get(s)+"");
        }

    }

}